<template>
  <div>
    <h1>{{id?'编辑':'新建'}}分类 </h1>
    <el-form @submit.native.prevent="save" label-width="120px" label-position="right">
      <el-form-item label="上级名称">
        <el-select v-model="model.parents" placeholder="">
          <el-option v-for="item in parents" :key="item._id" :label="item.name" :value="item._id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="名称" >
        <el-input v-model="model.name" placeholder=""></el-input>
      </el-form-item>
      <el-form-item >
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data () {
    return {
      model: {
        name: ''
      },
      // 上级名称
      parents: []
    }
  },
  props: {
    id: {}
  },
  methods: {
    // 点击按钮提交
    async save () {
      // this.$http.post('categories', this.model).then(response => {
      //   // console.log(response)
      //   this.$router.push('/categories/list')
      //   this.$message.success('保存成功')
      // })
      let res
      if (this.id) {
        // 编辑提交
        res = await this.$http.put(`rest/categories/${this.id}`, this.model)
      } else {
        // 新增提交
        res = await this.$http.post('rest/categories', this.model)
      }
      console.log(res)
      // 注意这里是前端页面路径，不需要加rest
      this.$router.push('/categories/list')
      this.$message.success('保存成功')
    },
    // 根据id获取编辑分类的信息
    async fetch () {
      const res = await this.$http.get(`rest/categories/${this.id}`)
      this.model = res.data
    },
    // 获取父级分类基本信息
    async fetchParents () {
      const res = await this.$http.get('rest/categories')
      this.parents = res.data
      console.log(this.parents)
    }
  },
  created () {
    this.id && this.fetch()
    this.fetchParents()
  }
}
</script>
